import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        System.out.println(main.isHappy(19));
    }
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null) return head;
        // 计算链表的长度
        int size = 1;
        ListNode tail = head;
        while (tail.next != null) {
            tail = tail.next;
            size++;
        }
         k=k%size;
        if(k==0) return head;
        while(k>0){
            ListNode cur=head.next;
            ListNode prev=head;
            while(cur.next!=null){
                cur=cur.next;
                prev=prev.next;
            }
            cur.next=head;
            prev.next=null;
            head=cur;
            k--;
        }
        return head;
    }
     static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode cur = head.next;
        head.next = null;
        while (cur != null) {
            ListNode curN = cur.next;
            cur.next = head;
            head = cur;
            cur = curN;
        }
        return head;
    }

    public boolean isHappy(int n) {
        if(n==1) return true;
        HashMap<Integer,Integer>map=new HashMap<>();
        while(true){
            map.put(n,map.getOrDefault(n,0)+1);
            if(map.get(n)!=1)return false;
            n=Calculatesquares(n);
            if(n==1) return true;
        }
    }

    private int Calculatesquares(int n) {
        if(n<10)return n*n;
        int sum=0;
        int flag=0;
        while(n>=10){
            flag=n%10;
            sum=flag*flag+sum;
            n=n/10;
        }
        return sum+n*n;
    }

}